import Input from '@/components/Input';
import NavBar from '@/components/NavBar';
import { getcodeAction, loginAction } from '@/store/action/user';
import { LocationStateType } from '@/utils/AuthRoute';
import { Toast } from 'antd-mobile';
import { useFormik } from 'formik';
import { useEffect, useRef, useState } from 'react';
import { useDispatch } from 'react-redux';
import { useHistory, useLocation } from 'react-router-dom';
import * as Yup from 'yup';
import styles from './index.module.scss';

export default function Login() {
  const location = useLocation<LocationStateType>();
  // 通过useFormik第三方库校验表单
  const formmik = useFormik({
    initialValues: {
      mobile: '',
      code: '',
    },
    onSubmit: async (values) => {
      console.log(values);
      // dispatch返回值为Promise 可设置async
      await dispatch(loginAction(values));
      // 跳转路由
      // 不能写死跳到首页 让它支持回跳原来的页面
      // 接收传来的fromPath，表示回跳到那个原来的页面
      const { state = {} as LocationStateType } = location;
      // state是可选参数，有可能为undefined，使用默认值处理回跳的路径
      const { fromPath = '/' } = state;
      // history.push(fromPath);
      // history对象中的历史记录
      // push会在历史记录，新增一条记录 ['login', '/layout/profile/', 'login', 'profile/edit']
      // replace
      history.replace(fromPath);
      // 提示用户
      Toast.show({ content: '登录成功', duration: 1000 });
    },
    validationSchema: Yup.object().shape({
      // 手机号校验
      mobile: Yup.string()
        .required('必填项')
        .matches(/^1[3-9]\d{9}$/, '手机号格式错误'),
      // 验证码校验
      code: Yup.string()
        .required('必填项')
        .matches(/^\d{6}$/, '验证码格式错误'),
    }),
  });
  const [second, setSecond] = useState(0);
  const dispatch = useDispatch();
  const timeRef = useRef<number>();
  const history = useHistory();
  useEffect(() => {
    return () => {
      // 组件卸载时清除定时器
      clearInterval(timeRef.current);
    };
  }, []);
  const handleCode = () => {
    // 判断没有手机号时，不允许执行
    if (formmik.errors.mobile) return;
    dispatch(getcodeAction(formmik.values.mobile));
    setSecond(60);
    // setInterval的类型会有两种 window和node.js会不同  node不是number类型
    timeRef.current = window.setInterval(() => {
      setSecond((preState) => {
        if (preState === 1) {
          clearInterval(timeRef.current);
        }
        return preState - 1;
      });
    }, 1000);
  };
  return (
    <div className={styles.root}>
      <NavBar>登录</NavBar>
      <div className="content">
        {/* 标题 */}
        <h3>短信登录</h3>
        <form onSubmit={formmik.handleSubmit}>
          {/* 手机号输入框 */}
          <Input
            autoFocus
            placeholder="请输入手机号"
            autoComplete="off"
            type="text"
            name="mobile"
            maxLength={11}
            // 移动端有一个touched属性，表示是否触摸过改字段
            //  touched 和 onBlur配合使用
            errorMsg={formmik.touched.mobile ? formmik.errors.mobile : ''}
            onBlur={formmik.handleBlur}
            value={formmik.values.mobile}
            onChange={formmik.handleChange}
          />
          {/* 短信验证码输入框 */}
          <Input
            placeholder="请输入验证码"
            autoComplete="off"
            type="text"
            name="code"
            maxLength={6}
            errorMsg={formmik.touched.code ? formmik.errors.code : ''}
            onBlur={formmik.handleBlur}
            extra={
              <span onClick={handleCode}>
                {second === 0 ? '获取验证码' : `${second}后获取验证码`}
              </span>
            }
            value={formmik.values.code}
            onChange={formmik.handleChange}
          />

          {/* 登录按钮 */}
          <button type="submit" className="login-btn" disabled={!formmik.isValid}>
            登录
          </button>
        </form>
      </div>
    </div>
  );
}
